﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BoxManager : MonoBehaviour
{
    private BoxCollider2D box;
    private Rigidbody2D rb;

    public LayerMask ground;

    public bool onGround = false;

    // Start is called before the first frame update
    void Start()
    {
        box = GetComponent<BoxCollider2D>();
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (box.IsTouchingLayers(ground))
        {
            rb.bodyType = RigidbodyType2D.Static;
            onGround = true;
        }
        else if(!onGround)
        {
            rb.bodyType = RigidbodyType2D.Dynamic;
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.transform.tag == "Player")
        {
            if (collision.transform.position.y > gameObject.transform.position.y)
            {
                StartCoroutine(DestoryMe());
            }
        }
    }

    IEnumerator DestoryMe()
    {
        yield return new WaitForSeconds(1f);

        Destroy(this.gameObject);
    }
}
